import React from 'react';
import { useDeviceWebSocket } from '../utils/websocket';
import { DeviceAPI } from '../apis/device';
import ScreenDisplay from './ScreenDisplay';

interface DevicePanelProps {
  // 定义props类型
}

const DevicePanel: React.FC<DevicePanelProps> = () => {
  const [selectedDevice, setSelectedDevice] = React.useState<string>('');
  const [deviceInfo, setDeviceInfo] = React.useState<string>('');
  const [screenData, setScreenData] = React.useState<string>('');
  const [devices, setDevices] = React.useState<Array<{id: string, name: string}>>([]);
  const [loading, setLoading] = React.useState<boolean>(false);
  const [error, setError] = React.useState<string>('');
  
  // 使用WebSocket hook
  useDeviceWebSocket(selectedDevice, setScreenData);

  // 从API获取设备列表
  React.useEffect(() => {
    async function fetchDevices() {
      setLoading(true);
      setError('');
      try {
        const data = await DeviceAPI.getDevices();
        setDevices(data);
      } catch (err) {
        setError('获取设备列表失败');
      } finally {
        setLoading(false);
      }
    }
    fetchDevices();
  }, []);
  //模拟设备操作事件
  const raiseEvent = (event: string, data: any) => {
    console.log(`模拟${event}事件:`, data);
    // 这里可以添加实际的设备操作逻辑
    if(event === 'click') {
        try {
            DeviceAPI.emulateDeviceClick(selectedDevice, data.x, data.y);
        }
        catch(err) {
            console.error('模拟点击失败:', err);
        }
    }
    else if(event === 'swipe') {
        try {
            DeviceAPI.emulateDeviceSwipe(selectedDevice, data.x1, data.y1, data.x2, data.y2);
        }
        catch(err) {
            console.error('模拟滑动失败:', err);
        }
    }
  }
  return (
    <div className="device-panel">
      <h3>设备列表</h3>
      {loading ? (
        <div>加载中...</div>
      ) : error ? (
        <div className="error-message">{error}</div>
      ) : (
        <>
          <select 
            value={selectedDevice}
            onChange={(e) => setSelectedDevice(e.target.value)}
          >
            <option value="">请选择设备</option>
            {devices.map(device => (
              <option key={device.id} value={device.id}>
                {device.name}
              </option>
            ))}
          </select>
          
          <ScreenDisplay 
            screenData={screenData}
            backgroundColor="#f0f0f0"
            raiseEvent={raiseEvent}
          />
          
          <textarea 
            value={deviceInfo}
            readOnly
            className="info-text"
          />
        </>
      )}
    </div>
  );
};

export default DevicePanel;